package top.oylan.mp.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import top.oylan.mp.entity.Role;
import top.oylan.mp.entity.RoleMenu;
import top.oylan.mp.entity.example.RoleExample;
import top.oylan.mp.entity.example.RoleMenuExample;
import top.oylan.mp.mapper.RoleMapper;
import top.oylan.mp.mapper.RoleMenuMapper;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class RoleService {

    @Resource
    RoleMapper roleMapper;

    public List<Role> selectAll(byte status) {
        RoleExample example = new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria();
        if (status < 2 && status >= 0) {
            criteria.andStatusEqualTo(status);
        }
        return roleMapper.selectByExample(example);
    }

    public void update(Role role) {
        roleMapper.updateByPrimaryKeySelective(role);
    }

    public void add(Role role) {
        roleMapper.insertSelective(role);
    }

    public void delete(Integer id) {
        roleMapper.deleteByPrimaryKey(id);
    }

    public void saveRoleMenus(JSONObject params) {
        List<RoleMenu> list = new ArrayList<>();
        JSONArray keys = params.getJSONArray("keys");
        int roleId = params.getIntValue("roleId");
        this.deleteRoleMenusByRoleId(roleId);
        for (int i = 0; i < keys.size(); i++) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(keys.getIntValue(i));
            list.add(roleMenu);
        }
        roleMapper.saveRoleMenus(list);
    }

    @Resource
    RoleMenuMapper roleMenuMapper;

    private void deleteRoleMenusByRoleId(int roleId) {
        RoleMenuExample example = new RoleMenuExample();
        RoleMenuExample.Criteria criteria = example.createCriteria();
        criteria.andRoleIdEqualTo(roleId);
        roleMenuMapper.deleteByExample(example);
    }
}
